import email
from email.header import Header
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.mime.base import MIMEBase
import os.path
import time
import os
import run_test
def require_report():
    result_dir = './report'
    lists = os.listdir(result_dir)
    lists.sort(key=lambda fn: os.path.getmtime(result_dir + "\\" + fn))
    # print(('最新的文件为：' + lists[-1]))
    # file_name = os.path.join(result_dir, lists[-1])
    file_name = os.path.join(result_dir, run_test.emial_filename)
    return file_name
def require_new_report():
    result_dir = './report'
    lists = os.listdir(result_dir)
    lists.sort(key=lambda fn: os.path.getmtime(result_dir + "\\" + fn))
    print(('最新的文件为：' + lists[-1]))
    file_name = os.path.join(result_dir, lists[-1])
    return file_name
# 用smtp发送邮件
def send_email(email_address = 'sd452555563@sina.com',email_password = 'naruto20111992',text='sd1243920647@sina.com'):
    file_name1 = require_report()
    if file_name1 == './report\\None':
        file_name1 = require_new_report()
    # file_name1 = run_test.emial_filename
    # print(file_name1)
    if email_address == '':
        email_address = 'sd1243920647@sina.com'
        email_password = 'naruto20111992'
    From = email_address
    # To = "sd1243920647@sina.com"
    # file_name = r"C:\\Users\\Administrator\\Desktop\\page_object\\report\\555.txt"  # 附件名
    server = smtplib.SMTP("smtp.sina.com")
    server.login(email_address,email_password)  # 仅smtp服务器需要验证时
    main_msg = MIMEMultipart()  # 构造MIMEMultipart对象做为根容器
    #  构造MIMEText对象做为邮件显示内容并附加到根容器
    now = time.strftime("%Y-%m-%d %H:%M:%S")
    text_msg = MIMEText("这是一份时间为" + str(now) + "的测试报告", 'html', 'utf-8')
    main_msg.attach(text_msg)
    # 构造MIMEBase对象做为文件附件内容并附加到根容器
    contype = 'application/octet-stream'
    maintype, subtype = contype.split('/', 1)
    # 读入文件内容并格式化 [方式2]－－－－－－－－－－－－－－－－－－－－－－－－－－－－－－
    data = open(str(file_name1), 'rb')
    file_msg = MIMEBase(maintype, subtype)
    file_msg.set_payload(data.read())
    data.close()
    email.encoders.encode_base64(file_msg)  # 把附件编码
    # ## 设置附件头
    basename = os.path.basename(file_name1)
    file_msg.add_header('Content-Disposition', 'attachment', filename=basename)  # 修改邮件头
    main_msg.attach(file_msg)
    #  设置根容器属性
    main_msg['From'] = From
    main_msg['To'] = text
    main_msg['Subject'] = Header("自动化测试报告", 'utf-8')
    main_msg['Date'] = email.utils.formatdate()
    # 得到格式化后的完整文本
    fullText = main_msg.as_string()
    try:
        server.sendmail(From, text, fullText)
    finally:
        server.quit()
    print("已发送测试报告至："+str(text))
if __name__ == '__main__':
    send_email()